import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Navigation,
  Zap,
  Edit,
  MoreHorizontal,
  Ruler,
  Wind,
  FileText,
  Trash2,
  BarChart2,
  FileDown,
  Brain,
  Lightbulb,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { useToast } from "@/components/ui/use-toast";
import { Link } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import SmartRecommendationModal from "./SmartRecommendationModal";
import { RecommendAPI } from "@/api/Recommends";

// 常量定义 - 集中管理映射关系和静态数据
const CONSTANTS = {
  // 施工方法标签映射
  methodLabelMap: {
    helicopterStringing: "直升机展放",
    droneStringing: "无人机牵引",
    rocketStringing: "火箭炮牵引",
    cablePulling: "地面牵引",
    towerCrane: "塔式起重机",
    mobileCrane: "汽车起重机",
    manualStringing: "人工架线",
    scaffoldingErection: "搭设跨越架",
    vehicleStringing: "车辆牵引",
  },

  // 施工方法类型颜色映射
  methodTypeColors: {
    helicopterStringing: "bg-purple-100 text-purple-800",
    droneStringing: "bg-blue-100 text-blue-800",
    rocketStringing: "bg-orange-100 text-orange-800",
    cablePulling: "bg-green-100 text-green-800",
    scaffoldingErection: "bg-red-100 text-red-800",
    manualStringing: "bg-gray-100 text-gray-800",
    mobileCrane: "bg-yellow-100 text-yellow-800",
  },

  // 类型图标映射
  typeIcons: {
    highway: "🛣️",
    railway: "🚆",
    river: "🌊",
    cable: "🔌",
    pipeline: "🔧",
    building: "🏢",
    forest: "🌲",
    other: "📍",
  },

  // 难度级别文本映射
  difficultyTexts: {
    low: "低难度",
    medium: "中等难度",
    high: "高难度",
    critical: "极高难度",
  },

  // 优先级文本映射
  priorityTexts: {
    low: "低优先级",
    medium: "中等优先级",
    high: "高优先级",
    urgent: "紧急",
  },

  // 状态文本映射
  statusTexts: {
    planning: "规划中",
    designed: "已设计",
    approved: "已批准",
    construction: "施工中",
    completed: "已完成",
  },

  // 跨越类型场景映射
  crossingTypeScenarios: {
    highway: "公路跨越场景",
    railway: "铁路跨越场景",
    river: "河流跨越场景",
  },
};

// 颜色工具函数 - 提取为独立函数
const getDifficultyColor = (level) => {
  const colors = {
    low: "bg-green-100 text-green-800 border-green-200",
    medium: "bg-yellow-100 text-yellow-800 border-yellow-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    critical: "bg-red-100 text-red-800 border-red-200",
  };
  return colors[level] || colors.medium;
};

const getPriorityColor = (priority) => {
  const colors = {
    low: "bg-gray-100 text-gray-800",
    medium: "bg-blue-100 text-blue-800",
    high: "bg-orange-100 text-orange-800",
    urgent: "bg-red-100 text-red-800",
  };
  return colors[priority] || colors.medium;
};

const getStatusColor = (status) => {
  const colors = {
    planning: "bg-gray-100 text-gray-800",
    designed: "bg-blue-100 text-blue-800",
    approved: "bg-green-100 text-green-800",
    construction: "bg-yellow-100 text-yellow-800",
    completed: "bg-emerald-100 text-emerald-800",
  };
  return colors[status] || colors.planning;
};

export default function CrossingPointCard({
  point = {},
  project = null,
  projectName = "",
  latestScheme = null,
  onEdit,
  onEditScheme,
  onCreateScheme,
  onManualCreateScheme,
  onDelete,
  onSystemRatingRecommendation,
  onOpenRatingModal,
}) {
  // 状态管理
  const [isGeneratingDoc, setIsGeneratingDoc] = useState(false);
  const [showRecommendationModal, setShowRecommendationModal] = useState(false);
  const [recommendationData, setRecommendationData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();
  const [useMockData, setUseMockData] = useState(false); // 新增：模拟数据开关状态

  // 获取类型图标
  const getTypeIcon = (type) => {
    return CONSTANTS.typeIcons[type] || "📍";
  };

 

  // 处理编辑
  const handleEdit = () => {
    if (typeof onEdit === "function") {
      onEdit(point);
    }
  };

 

  // 生成模拟推荐数据
  const generateMockRecommendation = (scheme) => {
    const baseScenario = scheme.crossingType
      ? CONSTANTS.crossingTypeScenarios[scheme.crossingType] || "通用场景"
      : "通用场景";

    return {
      code: 0,
      data: {
        advantages: [
          "施工效率高，相比传统方法可缩短工期30%",
          "安全性高，采用双重防护措施",
          "对周边环境影响小，符合环保要求",
          "材料消耗低，可节约成本约15%",
        ],
        alternativeMethods: [
          {
            alternativeMethod: {
              applicableScenarios: ["跨越高速公路", "跨越二级以下公路"],
              changeLog: "V1.0 (2023-05-10): 初始版本",
              commonEmergencyMeasureIds: ["EM-2023-001", "EM-2023-005"],
              commonEmergencyMeasures: [
                {
                  category: "设备故障",
                  code: "EM-2023-001",
                  createdDate: "2023-03-15",
                  delFlag: "0",
                  description: "应对起重机突发故障的应急措施",
                  id: "1001",
                  immediateActions: "立即停止作业，设置警示标志，启用备用设备",
                  incidentType: "设备故障",
                  requiredEquipment: "备用起重机、警示灯、警示带",
                  responsiblePersonRole: "现场负责人",
                  updatedDate: "2023-04-20",
                },
              ],
              compilationBasisIds: ["STD-2022-001", "STD-2022-003"],
              constructionSteps: [
                {
                  associatedRiskCodes: ["RISK-001", "RISK-003"],
                  description: "搭建临时支撑结构，确保施工安全",
                  durationDays: 2,
                  environmentalMeasures: ["设置防尘网", "噪声监测"],
                  id: 1,
                  predecessorsStep: [],
                  qualityMeasures: ["每日检查支撑结构稳定性"],
                  requiredEquipment: [
                    {
                      name: "起重机",
                      quantity: 1,
                      specification: "25t",
                      unit: "台",
                    },
                    {
                      name: "脚手架",
                      quantity: 10,
                      specification: "标准型",
                      unit: "套",
                    },
                  ],
                  requiredMaterials: [
                    {
                      name: "钢管",
                      quantity: 50,
                      specification: "φ100mm",
                      unit: "根",
                    },
                  ],
                  requiredPersonnel: [
                    {
                      qualification: "起重机械操作员证",
                      quantity: 2,
                      role: "起重机操作员",
                    },
                    {
                      qualification: "架子工证",
                      quantity: 4,
                      role: "架子工",
                    },
                  ],
                  requiredVehicles: [
                    {
                      licensePlate: "",
                      quantity: 1,
                      type: "货车",
                    },
                  ],
                  safetyMeasures: ["佩戴安全帽", "设置安全警示区"],
                  standardWorkCategories: ["基础施工"],
                  stepName: "临时支撑搭建",
                  stepOrder: 1,
                  technicalMeasures: ["严格按照设计图纸施工"],
                  templateId: "STEP-TPL-001",
                },
                {
                  associatedRiskCodes: ["RISK-002"],
                  description: "进行导线架设作业",
                  durationDays: 3,
                  environmentalMeasures: ["防止导线坠落保护措施"],
                  id: 2,
                  predecessorsStep: [1],
                  qualityMeasures: ["导线张力测试"],
                  requiredEquipment: [
                    {
                      name: "张力机",
                      quantity: 1,
                      specification: "",
                      unit: "台",
                    },
                  ],
                  requiredMaterials: [
                    {
                      name: "导线",
                      quantity: 200,
                      specification: "LGJ-400",
                      unit: "米",
                    },
                  ],
                  requiredPersonnel: [
                    {
                      qualification: "高空作业证",
                      quantity: 6,
                      role: "架设工",
                    },
                  ],
                  requiredVehicles: [],
                  safetyMeasures: ["双钩安全带", "防坠器"],
                  standardWorkCategories: ["线路架设"],
                  stepName: "导线架设",
                  stepOrder: 2,
                  technicalMeasures: ["采用张力放线技术"],
                  templateId: "STEP-TPL-002",
                },
              ],
              createdDate: "2023-01-15",
              description: "适用于中等跨度的跨越施工方法，采用悬索跨越技术",
              documentTemplateId: "DOC-TPL-002",
              engineeringFactors: {
                angleFactorRules: [
                  {
                    multiplier: 1.0,
                    threshold: 30,
                  },
                  {
                    multiplier: 1.2,
                    threshold: 60,
                  },
                ],
                heightFactorRules: [
                  {
                    multiplier: 1.0,
                    threshold: 10,
                  },
                  {
                    multiplier: 1.3,
                    threshold: 20,
                  },
                ],
                nettingFactorRules: [
                  {
                    multiplier: 1.0,
                    threshold: 50,
                  },
                ],
                spanFactorRules: [
                  {
                    multiplier: 1.0,
                    threshold: 100,
                  },
                  {
                    multiplier: 1.5,
                    threshold: 200,
                  },
                ],
                typeFactorMultipliers: [
                  {
                    multiplier: 1.0,
                    type: "highwayGradePlus2",
                  },
                  {
                    multiplier: 1.2,
                    type: "firstHighway",
                  },
                ],
                widthFactorRules: [
                  {
                    multiplier: 1.0,
                    threshold: 20,
                  },
                  {
                    multiplier: 1.2,
                    threshold: 40,
                  },
                ],
              },
              id: "11ebb6a2805749f790757154837ea365",
              methodCode: "CM-2023-002",
              methodName: "悬索式跨越施工法",
              parentTemplateId: "",
              updatedDate: "2023-04-10",
              version: "1.1",
            },
            reason: "适用于跨度较大的场景，但施工成本较高",
          },
        ],
        confidence: 0.85,
        considerations: [
          "施工期间需注意天气变化，遇大风天气应停止作业",
          "需提前与交通部门协调，做好交通疏导方案",
          "施工前应对所有参与人员进行专项培训",
        ],
        methodTemplate: {
          id: "11ebb6a2805749f790757154837ea365",
          methodName: "脚手架跨越施工法",
          applicableScenarios: ["跨越二级以下公路", "跨越不通航河流"],
          description:
            "采用落地式脚手架作为支撑体系的跨越施工方法，适用于中低高度、中小跨度的跨越工程",
          constructionSteps: [
            {
              stepOrder: 1,
              stepName: "地基处理",
              description: "对脚手架基础进行加固处理",
              durationDays: 1,
            },
            {
              stepOrder: 2,
              stepName: "脚手架搭设",
              description: "按照设计要求搭设跨越脚手架",
              durationDays: 3,
            },
          ],
        },
        reasoning:
          "根据该跨越点的参数分析（跨度80米，高度15米，二级公路），脚手架跨越施工法最为适用，具有成本低、安全性高、施工难度小等优势。该方法在类似工程中有多次成功应用案例，综合匹配度达85%。",
      },
      msg: "success",
    };
  };

  // 模拟数据 - 智能推荐逻辑
  const handleSmartRecommendation = async () => {
    setIsLoading(true);
    try {
      // 获取当前方案ID
      const currentScheme = latestScheme || point;
      if (!currentScheme?.id) {
        throw new Error("未找到有效的跨越点ID，请先完善方案基础信息");
      }

      // 模拟接口调用延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 生成模拟数据
      const mockData = generateMockRecommendation(currentScheme);
      if (!mockData || mockData.code !== 0 || !mockData.data) {
        throw new Error("模拟数据生成失败");
      }

      // 保存推荐数据并打开弹窗
      setRecommendationData(mockData.data);
      setShowRecommendationModal(true);

      toast({
        title: "推荐成功",
        description: "已为您生成智能推荐方案",
      });
    } catch (error) {
      console.error("智能推荐失败:", error);
      toast({
        variant: "destructive",
        title: "推荐失败",
        description: error.message || "生成智能推荐时发生错误，请稍后重试",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 手动创建方案
  const handleManualCreate = () => {
    if (typeof onManualCreateScheme === "function") {
      onManualCreateScheme(point);
    }
  };

  // 处理删除
  const handleDelete = () => {
    if (typeof onDelete === "function") {
      onDelete(point.id);
    }
  };

  // 生成文档
  const handleGenerateDocument = async () => {
    if (!latestScheme) return;

    setIsGeneratingDoc(true);
    try {
      const response = await ConstructionSchemeAPI.exportWord(latestScheme.id);

      if (!(response.data instanceof Blob)) {
        throw new Error("后端返回的不是二进制文件流，可能接口出错");
      }

      const rawFileName =
        response.headers["download-filename"] ||
        response.headers["Download-Filename"];

      let downloadFileName = rawFileName
        ? decodeURIComponent(rawFileName)
        : `施工方案_${latestScheme.name || latestScheme.id}.docx`;

      if (!downloadFileName.endsWith(".docx")) {
        downloadFileName += ".docx";
      }

      const wordMimeType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const fileBlob = new Blob([response.data], { type: wordMimeType });

      if (response.size) {
        toast({
          title: "未选择文档模板",
          description: "方案信息不完整，无法生成文档",
        });
        return;
      }

      // 下载文件
      const url = window.URL.createObjectURL(fileBlob);
      const a = document.createElement("a");
      a.href = url;
      a.download = downloadFileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error("生成文档错误:", error);
      toast({
        variant: "destructive",
        title: "生成Word失败",
        description: "方案信息不完整/未选择文档模板，无法进行分析。",
      });
    } finally {
      setIsGeneratingDoc(false);
    }
  };

  // 创建方案
  const handleCreateScheme = async (method) => {
    if (!point || !method) {
      toast({
        variant: "destructive",
        title: "创建失败",
        description: "缺少必要的参数",
      });
      return;
    }

    try {
      const schemeData = {
        crossingPointId: point.id,
        name: `${point.name}施工方案`,
        version: "1.0",
        approvalStatus: "draft",
        constructionMethod: method.method,
        methodReasoning: method.reasoning,
        totalDuration: method.estimatedDuration,
        costEstimation: method.estimatedCost,
        weatherRequirements:
          method.method === "helicopterStringing"
            ? "风力不超过6级，无降雨"
            : "正常天气条件",
        riskAssessment: method.disadvantages.join("；"),
      };

      if (typeof onCreateScheme === "function") {
        onCreateScheme(schemeData);
      }
      setShowRecommendationModal(false);
    } catch (error) {
      console.error("创建方案失败:", error);
      toast({
        variant: "destructive",
        title: "创建失败",
        description: `创建施工方案时出错: ${error.message}`,
      });
    }
  };

  // 渲染表格数据项（单个单元格内容）
  const renderTableItem = (icon, label, value) => {
    if (value === undefined || value === null || value === "") return null;
    return (
      <tr className="hover:bg-gray-50 transition-colors">
        <td className="px-3 py-2 text-sm text-gray-600 border-b border-gray-100">
          <div className="flex items-center">{icon} <span className="ml-2">{label}</span></div>
        </td>
        <td className="px-3 py-2 text-sm text-gray-800 border-b border-gray-100 font-medium">
          {value}
        </td>
      </tr>
    );
  };

  return (
    <div>
      <Card className="group hover:shadow-xl transition-all duration-300 border-0 shadow-lg bg-white flex flex-col">
        <CardHeader className="pb-4">
          <div className="flex items-start justify-between">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-gradient-to-br from-blue-100 to-blue-200 rounded-xl flex items-center justify-center text-xl">
                {getTypeIcon(point.crossingType)}
              </div>
              <div>
                <CardTitle className="text-lg font-bold text-gray-900">
                  {point.name || "未命名跨越点"}
                </CardTitle>
                <p className="text-sm text-gray-500 mt-1">
                  {projectName || "未关联项目"}
                </p>
              </div>
            </div>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <MoreHorizontal className="w-4 h-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem onClick={handleEdit}>
                  <Edit className="w-4 h-4 mr-2" />
                  编辑跨越点
                </DropdownMenuItem>

                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={handleDelete}
                  className="text-red-600"
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  删除
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </CardHeader>

        <CardContent className="flex-1 space-y-6 px-6">
          {/* 核心数据表格 - 替换原列表展示 */}
          <div className="overflow-x-auto rounded-lg border border-gray-100">
            <table className="w-full text-left">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-3 py-3 text-sm font-semibold text-gray-700 border-b border-gray-200">
                    属性名称
                  </th>
                  <th className="px-3 py-3 text-sm font-semibold text-gray-700 border-b border-gray-200">
                    属性值
                  </th>
                </tr>
              </thead>
              <tbody>
                {renderTableItem(
                  <Navigation className="w-4 h-4" />,
                  "跨越对象",
                  point.crossingObject || "未指定"
                )}
                {renderTableItem(
                  <Ruler className="w-4 h-4" />,
                  "被跨越物宽度",
                  point.crossedObjectWidth ? `${point.crossedObjectWidth}m` : null
                )}
                {renderTableItem(
                  <Navigation className="w-4 h-4" />,
                  "交叉角度",
                  point.crossingAngle ? `${point.crossingAngle}°` : null
                )}
                {renderTableItem(
                  <Ruler className="w-4 h-4" />,
                  "档距",
                  point.spanLength ? `${point.spanLength}m` : null
                )}
                {renderTableItem(
                  <Zap className="w-4 h-4" />,
                  "高度",
                  point.crossingHeight ? `${point.crossingHeight}m` : null
                )}
                {renderTableItem(
                  <Wind className="w-4 h-4" />,
                  "设计风速",
                  point.windSpeed ? `${point.windSpeed}m/s` : null
                )}
              </tbody>
            </table>
          </div>

          {/* 当前方案信息卡片 */}
          {latestScheme && (
            <div className="mt-2 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <div className="flex items-center justify-between mb-3">
                <h4 className="font-medium text-blue-900 text-sm">当前方案</h4>
              </div>
              <div className="space-y-2">
                <Link
                  to={createPageUrl(`SchemeAnalysis?id=${latestScheme.id}`)}
                  className="text-sm font-medium text-blue-800 hover:text-blue-600 block"
                >
                  {latestScheme.name}
                </Link>
                <div className="grid grid-cols-2 gap-2 text-xs text-blue-600">
                  {latestScheme.version && (
                    <div>版本: {latestScheme.version}</div>
                  )}
                  {latestScheme.totalDuration && (
                    <div>工期: {latestScheme.totalDuration}天</div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* 状态标签区域 */}
          <div className="flex flex-wrap gap-2 pt-2">
            <Badge className={`${getDifficultyColor(point.difficultyLevel)} px-2 py-1`}>
              {CONSTANTS.difficultyTexts[point.difficultyLevel] ||
                CONSTANTS.difficultyTexts.medium}
            </Badge>
            <Badge className={`${getPriorityColor(point.priority)} px-2 py-1`}>
              {CONSTANTS.priorityTexts[point.priority] ||
                CONSTANTS.priorityTexts.medium}
            </Badge>
            <Badge className={`${getStatusColor(point.status)} px-2 py-1`}>
              {CONSTANTS.statusTexts[point.status] ||
                CONSTANTS.statusTexts.planning}
            </Badge>
          </div>
        </CardContent>

        {/* 操作按钮区域 */}
        <div className="p-6 pt-0 mt-auto">
          <div className="space-y-3">
            {latestScheme ? (
              <div className="space-y-3">
                {onEditScheme ? (
                  <Button
                    onClick={() => onEditScheme(latestScheme)}
                    className="w-full bg-green-600 hover:bg-green-700"
                  >
                    <BarChart2 className="w-4 h-4 mr-2" />
                    方案分析优化
                  </Button>
                ) : (
                  <Link
                    to={createPageUrl(`SchemeAnalysis?id=${latestScheme.id}`)}
                    className="w-full"
                  >
                    <Button className="w-full bg-green-600 hover:bg-green-700">
                      <BarChart2 className="w-4 h-4 mr-2" />
                      方案分析优化
                    </Button>
                  </Link>
                )}

                <Button
                  onClick={handleGenerateDocument}
                  disabled={isGeneratingDoc}
                  variant="outline"
                  size="sm"
                  className="w-full bg-white text-gray-700 border-gray-200"
                >
                  {isGeneratingDoc ? (
                    <>
                      <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-600 mr-1"></div>
                      生成中...
                    </>
                  ) : (
                    <>
                      <FileDown className="w-3 h-3 mr-1" />
                      生成Word
                    </>
                  )}
                </Button>
              </div>
            ) : (
              <div className="space-y-3">
                <Button
                  onClick={handleManualCreate}
                  variant="outline"
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium"
                >
                  <FileText className="w-4 h-4 mr-2" />
                  手动创建方案
                </Button>
                <Button
                  onClick={handleSmartRecommendation}
                  disabled={isLoading}
                  className="w-full text-white bg-purple-600 hover:bg-purple-700  text-white transition-colors"

                >
                  {isLoading ? (
                    <>
                      <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-1"></div>
                      推荐中...
                    </>
                  ) : (
                    <>
                      <Lightbulb className="w-4 h-4 mr-2" />
                      智能推荐
                    </>
                  )}
                </Button>
              </div>
            )}
          </div>
        </div>
      </Card>

      {/* 智能推荐弹窗 */}
      <SmartRecommendationModal
        isOpen={showRecommendationModal}
        onClose={() => setShowRecommendationModal(false)}
        crossingPoint={point}
        recommendation={recommendationData}
        onSchemeCreated={handleCreateScheme}
      />
    </div>
  );
}